const sip = require("sip");
const log4js = require('../../../utils/logUtils');
const logger = log4js.getLogger('sip');
const deviceCache = require('../../../db/deviceCache');
const sipUtils = require("../../../utils/sipUtils");
const config = require("../../../db/config");
const clientUtils = require("./clientUtils");

const TAG = "[向上级连] [发送心跳]";
module.exports = {
    interval:null,
    /**
     * interval channel
     * @param {*} content
     */
    INTERVAL_CHANNEL(content) {
        const that = this;
        if (!that.interval) {
            logger.info(TAG, '启动定时任务,每分钟执行一次');
            that.interval = setInterval(async function () {
                // 发送keepalive信息
                await that.KEEPALIVE_CHANNEL(content);
            }, 60 * 1000);
        }
    },
    /**
     * 心跳，主通道
     * @param {*} content
     */
    async KEEPALIVE_CHANNEL(content) {
        const {upwardUri, self_account } = await clientUtils.generateClientParams();
        sip.send({
            method: 'MESSAGE',
            uri: upwardUri, version: config.sip.version,
            content: '<?xml version="1.0" encoding="GB2312" ?>' +
                '<Notify>' +
                '<CmdType>Keepalive</CmdType>' +
                '<SN>' + sipUtils.generateSN() + '</SN>' +
                '<DeviceID>' + self_account + '</DeviceID>' +
                '<Status>OK</Status>' +
                '</Notify>',
            headers: {
                from: {uri: deviceCache.localUri, params: {tag: sipUtils.rstring()}},
                to: {uri: deviceCache.localUri},
                'call-id': sipUtils.rstring(),
                cseq: {method: 'MESSAGE', seq: sipUtils.rstring()},
                'Content-Type': 'Application/MANSCDP+xml',
                'Max-Forwards': 70
            }
        }, function (rs) {
            if (rs.status === 200) {
                logger.info(TAG, '发送 keepalive 成功');
            } else {
                logger.trace(TAG,'发送 keepalive 失败', rs);
            }
        });
    }
}
